package com.ooqiu.gaming.ui.login;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.base.BaseActivity;
import com.ooqiu.gaming.common.entities.GamingUser;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.bind.BindPhoneActivity;
import com.ooqiu.gaming.ui.register.RegisterActivity;
import com.ooqiu.gaming.ui.web.X5WebView;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.gaming.utils.RxCountDown;
import com.ooqiu.gaming.view.ToastUtil;
import com.ooqiu.gaming.view.Topbar;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

@Route(path = DynamicLoginActivity.PATH)
public class DynamicLoginActivity extends BaseActivity {
    public static final String PATH = "/gn/dynamic_login";
    @BindView(R.id.topbar)
    Topbar mTopbar;
    @BindView(R.id.edit_mobile)
    EditText mEditMobile;
    @BindView(R.id.edit_pwd)
    EditText mEditPwd;
    @BindView(R.id.tv_countdown)
    TextView mTvCountdown;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.btn_dynamic_login)
    Button mBtnDynamicLogin;
    @BindView(R.id.img_qq)
    CircleImageView mImgQq;
    @BindView(R.id.img_wechat)
    CircleImageView mImgWechat;
    @BindView(R.id.img_sina)
    CircleImageView mImgSina;
    @BindView(R.id.tv_look)
    TextView mTvLook;
    @BindView(R.id.tv_have_que)
    TextView mTvHaveQue;


    GamingApi mGamingApi;

    UserStorage mUserStorage;

    X5WebView mX5WebView;


    @Override
    public int initContentView() {
        return R.layout.activity_dynamic_login;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        mGamingApi = getApplicationComponent().getGamingApi();
        mUserStorage = getApplicationComponent().getUserStorage();
    }

    @Override
    public void initUiAndListener() {

        mTopbar.setOnNavBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRouter().build(RegisterActivity.PATH).navigation();
                finish();
            }
        });

        mX5WebView = new X5WebView(this);

        mTopbar.setOnMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return null;
    }

    @Override
    protected View statusLayoutId() {
        return null;
    }


    @OnClick({R.id.tv_countdown, R.id.btn_login, R.id.btn_dynamic_login, R.id.img_qq, R.id.img_wechat, R.id.img_sina, R.id.tv_look, R.id.tv_have_que})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_countdown:
                if (!TextUtils.isEmpty(mEditMobile.getText())) {
                    fetchCode(mEditMobile.getText().toString());
                } else {
                    ToastUtil.showWarning("手机号不能为空");
                }
                break;
            case R.id.btn_login:
                loginCheck();
                break;
            case R.id.btn_dynamic_login:
                getRouter().build(LoginActivity.PATH).navigation();
                finish();
                break;
            case R.id.img_qq:
                authorization(SHARE_MEDIA.QQ);
                break;
            case R.id.img_wechat:
                authorization(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.img_sina:
                authorization(SHARE_MEDIA.SINA);
                break;
            case R.id.tv_look:
                finish();
                break;
            case R.id.tv_have_que:
                finish();
                break;
        }
    }



    private void authorization(SHARE_MEDIA share_media) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                LogUtil.e("onStart " + "授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                LogUtil.e("onComplete " + "授权完成");
                LogUtil.json(map);

                JSONObject parseMap = JSON.parseObject(JSON.toJSONString(map));
                if (share_media == SHARE_MEDIA.QQ) {
                    thirdLogin(1, parseMap.getString("openid"), parseMap.getString("name"), parseMap.getString("profile_image_url"));
                } else if (share_media == SHARE_MEDIA.SINA) {
                    thirdLogin(3, parseMap.getString("id"), parseMap.getString("name"), parseMap.getString("avatar_large"));
                } else if (share_media == SHARE_MEDIA.WEIXIN) {
                    thirdLogin(2, parseMap.getString("openid"), parseMap.getString("name"), parseMap.getString("avatar_large"));
                }

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                LogUtil.e("onError " + "授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtil.showWarning("用户取消登录");
            }
        });
    }


    private void thirdLogin(final int type, String open_id, String nickName, String face) {
        mGamingApi.thirdLogin(type, open_id, nickName, face)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<GamingUser>(mContext) {
                    @Override
                    public void onNext(GamingUser user) {
                        if (TextUtils.isEmpty(user.getMobile())) {
                            getRouter().build(BindPhoneActivity.PATH)
                                    .withInt("login_type", type)
                                    .withString("token", user.getToken())
                                    .navigation(DynamicLoginActivity.this, 1001);
                        } else {
                            mUserStorage.saveUser(user);
                            finish();
                        }
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }



    private void fetchCode(String mobile) {
        mGamingApi.fetchCode(mobile, 4)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<String>(mContext) {
                    @Override
                    public void onNext(String object) {
                        countdown();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void countdown() {
        RxCountDown.countdown(60)
                .subscribe(new DefaultObserver<Integer>() {
                    @Override
                    protected void onStart() {
                        mTvCountdown.setEnabled(false);
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mTvCountdown.setText(String.valueOf(integer));
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        mTvCountdown.setText("获取");
                        mTvCountdown.setEnabled(true);
                    }

                });
    }


    public void loginCheck() {

        if (TextUtils.isEmpty(mEditMobile.getText())) {
            ToastUtil.showWarning("手机号不能为空");
            return;
        }

        if (TextUtils.isEmpty(mEditPwd.getText())) {
            ToastUtil.showWarning("密码不能为空");
            return;
        }


        login(mEditMobile.getText().toString(), mEditPwd.getText().toString());

    }


    @Override
    public Drawable getStateBarDrawable() {
        return new ColorDrawable(Color.WHITE);
    }


    private void login(String mobile, String pwd) {
        mGamingApi.dynamicLogin(mobile, pwd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<GamingUser>(mContext) {
                    @Override
                    public void onNext(GamingUser user) {
                        mUserStorage.saveUser(user);



                        finish();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

}
